import 'package:flutter/material.dart';
import 'package:flutter_demo/components/cu_navigation_bar/cu_navigation_bar.dart';
import 'package:flutter_demo/providers/async_user_notifier.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class User extends StatefulWidget {
  const User({super.key});

  @override
  State<User> createState() => _UserState();
}

class _UserState extends State<User> {
  @override
  void initState() {
    // TODO: implement initState
    print("初始化了");
    super.initState();
  }

  Widget userInfoWidget(BuildContext ctx) {
    return Consumer(
      builder: (ctx, ref, child) {
        final userModel = ref.watch(asyncUserProvider);
        return userModel.when(
          data: (userModel) => Text(userModel?.name ?? "未登录"),
          error: (error, stackTrace) => Text(error.toString()),
          loading: () => const CircularProgressIndicator(),
        );
      },
    );
  }

  Widget loginOutWidget(BuildContext ctx) {
    return Consumer(
      builder: (ctx, ref, child) {
        return FilledButton(
          onPressed: () {
            ref.read(asyncUserProvider.notifier).logout();
          },
          child: const Text("退出登录"),
        );
      },
    );
  }

  Widget loginInWidget(BuildContext ctx) {
    return Consumer(
      builder: (ctx, ref, child) {
        return FilledButton.tonal(
          onPressed: () {
            ref.read(asyncUserProvider.notifier).loginIn();
          },
          child: const Text("登录"),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("个人中心")),
      body: SafeArea(
        child: Column(
          children: [
            userInfoWidget(context),
            loginOutWidget(context),
            loginInWidget(context),
          ],
        ),
      ),
      bottomNavigationBar: CuNavigationBar(),
    );
  }
}
